package qq2564874169.tuaotuao.fx;

import qq2564874169.tuaotuao.fx.utils.StringUtil;

import java.io.File;
import java.nio.file.FileSystems;

public class FxEnv {
    private static Class<?> mainClass;
    private static boolean isShutdown;

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            isShutdown = true;
        }));
    }

    public static boolean isShutdown() {
        return isShutdown;
    }

    public static void setMainClass(Class<?> mainClass) {
        FxEnv.mainClass = mainClass;
    }

    public static Class<?> getMainClass() {
        return mainClass;
    }

    public static String lineSeparator() {
        return System.lineSeparator();
    }

    public static String fileSeparator() {
        return FileSystems.getDefault().getSeparator();
    }

    public static String pathSeparator() {
        return File.pathSeparator;
    }

    public static String userDir() {
        return System.getProperty("user.dir");
    }

    public static String jarPath() {
        FxAssert.isNotNull(mainClass, "请先使用Env.setMainClass");
        String path = mainClass.getProtectionDomain().getCodeSource().getLocation().getPath();
        File file = new File(path);
        if (file.isDirectory() && file.exists()) {
            return null;
        } else if (file.isFile() && file.exists()) {
            return path;
        }
        int s = path.toLowerCase().indexOf(".jar!");
        if (s > -1) {
            return path.substring(0, s + 4);
        }
        return null;
    }

    public static String appDir() {
        String path = mainClass.getProtectionDomain().getCodeSource().getLocation().getPath();
        String dir = "";
        File file = new File(path);
        if (file.isDirectory() && file.exists()) {
            dir = StringUtil.trimRight(path, "/");
        } else {
            path = jarPath();
            if (path != null) {
                dir = StringUtil.trimRight(new File(path).getParent(), "/");
            }
        }
        if (System.getProperty("os.name", "").toLowerCase().contains("windows")) {
            dir = StringUtil.trimLeft(dir, "/");
        }
        return dir;
    }
}
